﻿//#version 120
uniform vec3 aNormal;
uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;
uniform vec3 uLightDirection;       //定向光方向

uniform vec3 lightColAttr;
uniform vec3 lightPosAttr;
uniform vec3 viewPosAttr;
uniform vec3 ambientColAttr;
uniform vec3 uLightSpecular;

attribute vec3 posAttr;
attribute vec3 colAttr;
attribute vec2 a_texcoord;

varying vec2 v_texcoord;
varying vec3 col;
varying vec3 pos;

varying vec4 vDiffuse;      //用于传递给片元着色器的散射光分量
varying vec4 vSpecular;     //用于传递给片元着色器的镜面光最终强度
varying vec4 vAmbient;      //环境光

void directionalLight(vec3 normal, vec3 lightDirection, vec4 lightDiffuse)
{
    vec3 normalTarget = posAttr + normal;
    vec3 newNormal = vec3((model*vec4(normalTarget, 1.0)) - (model*vec4(posAttr, 1.0)));
    newNormal = normalize(newNormal);

    vec3 vp = normalize(lightDirection);
    float nDotViewPosition = max(0.0, dot(newNormal, vp));
    vDiffuse=lightDiffuse*nDotViewPosition;

    vec3 eye = normalize(viewPosAttr-(model*vec4(posAttr, 1.0)));

    vec3 halfVector = normalize(vp+eye);   //视线与光线的半向量
    float shininess = 50.0;                 //粗糙度，越小越光滑
    float nDotViewHalfVector = dot(newNormal, halfVector);
    float powerFactor = max(0.0, pow(nDotViewHalfVector, shininess));

    vSpecular = vec4(uLightSpecular, 1.0) * powerFactor;
}

void pointLight(vec3 normal, vec3 lightLocation, vec4 lightDiffuse)
{
    vec3 normalTarget = posAttr + normal;
    vec3 newNormal = vec3((model*vec4(normalTarget, 1.0)) - (model*vec4(posAttr, 1.0)));
    newNormal = normalize(newNormal);

    vec3 vp = normalize(lightLocation-(model*vec4(posAttr, 1.0)));
    vp = normalize(vp);
    float nDotViewPosition = max(0.0, dot(newNormal, vp));

    vDiffuse=lightDiffuse*nDotViewPosition;

    vec3 eye = normalize(viewPosAttr-(model*vec4(posAttr, 1.0)));
    vec3 vp1 = normalize(lightPosAttr-(model*vec4(posAttr, 1.0)));

    vec3 halfVector = normalize(vp1+eye);   //视线与光线的半向量
    float shininess = 10.0;                 //粗糙度，越小越光滑
    float nDotViewHalfVector = dot(newNormal, halfVector);
    float powerFactor = max(0.0, pow(nDotViewHalfVector, shininess));

    vSpecular = vec4(uLightSpecular, 1.0) * powerFactor;
}

//! [0]
void main()
{
    gl_Position = projection * view * model * vec4(posAttr, 1.0);
    v_texcoord = a_texcoord;
    col = colAttr;
    pos = posAttr;

//    pointLight(normalize(aNormal), lightPosAttr, vec4(lightColAttr,1.0));
    directionalLight(normalize(aNormal), uLightDirection, vec4(lightColAttr,1.0));

    vAmbient = vec4(ambientColAttr, 1.0);

}
//! [0]
